/*
 * @Author: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @Date: 2023-11-13 15:25:52
 * @LastEditors: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @LastEditTime: 2023-12-25 16:40:41
 * @FilePath: \covue-main\lib\core\config.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 引入模板解析方法
const {  pageCompile,makeDir } = require('./compile')
const ora = require("ora")
const  axios = require('axios')
const { promisify } = require('util')
// console
const chalk = require('chalk')
const figlet =  require('figlet')
// inquirer,命令行交互
const inquirer = require('inquirer')
const { name } = require('commander')
//拉git应用
const download = promisify(require('download-git-repo'))
// 处理仓库数据
function formatData(list) {
  let arr = []
  let templateNameList = []
  for(let i=0;i<list.length;i++){
    let urlStr = `github.com:${list[i].full_name}#master`
    let name = list[i].name
    // console.log('item---',list[i].name)
    let obj = {name:name,url:urlStr }
    arr.push(obj)
    templateNameList.push(list[i].name)
  }
  return {arr,templateNameList}
}
// 匹配出需要拉取的仓库
function getGitUrl(list,name){
  let url = ''
  for(let i=0;i<list.length;i++){
    if(list[i].name===name){
      url = list[i].url
    }
  }
  return url
}
// 新建页面模板方法
async function getPage(props,pageType){
  const spinner = ora('页面生成中')
  spinner.start()
  if (props.isNeed) {
    makeDir(`${props.lowerName}`)
  }
  await pageCompile(`${pageType}.ejs`, props)
  console.log(
    '\r\n' +
      chalk.white.bgBlueBright.bold(
        figlet.textSync('add page success', {
          font: 'Standard',
          horizontalLayout: 'default',
          verticalLayout: 'default',
          width: 200,
          whitespaceBreak: true,
        })
      )
  )
  spinner.stop()
}
function spinnerMethod(name,spinner){

  console.log('✨✨ is creating a  pageTemplate', name + '\r\n')
  spinner.start()
  console.log('\r\n')
}
// 通过github接口拉取项目模板
async function getGithubProject(project,userName){
  const res = await axios.get(`https://api.github.com/users/${userName}/repos`)
  const responseObj = formatData(res.data)
 // console.log('responseObj',responseObj.templateNameList,projectType)
  const answer = await inquirer.prompt([
    {
      type: 'list',
      name: 'template',
      message: '请选择一个模板:',
      choices:responseObj.templateNameList
    }
  ])
  
  if (answer.template?answer.template:'template') {
    const spinner = ora('模板生成中');
    spinner.start();
    console.log('✨✨ is creating a  project',answer.template);
    try {
      await download(getGitUrl(responseObj.arr,answer.template), project?project:answer.template,{ clone: false });
      console.log('\r\n' + chalk.white.bgBlueBright.bold(figlet.textSync('create project success', {
        font: 'Standard',
        horizontalLayout: 'default',
        verticalLayout: 'default',
        width: 200,
        whitespaceBreak: true
      })));
      spinner.stop();
      // 拉取依赖，鉴于大家使用的拉包方式可能不一致，所以暂时不使用此功能
      // spinner2.start()
      // const command = process.platform === "win32" ? "npm.cmd" : "npm"
      // await terminalCommands(command, ['install'], { cwd: `./${project}` })
      // spinner2.stop()
     
    } catch (error) {
      spinner.fail('生成失败，请稍后再试');
      spinner.stop();
      console.log(error);
    }
  }
}
module.exports = {
  formatData,
  getGitUrl,
  getPage,
  spinnerMethod,
  getGithubProject
};